package com.csii.security.authentication.openid;

import com.csii.security.authentication.GeneralAuthenticationFailureHandler;
import com.csii.security.authentication.GeneralAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.stereotype.Component;

/**
 * 用于组合其他关于手机登录的组件
 * @Auther: ian
 */
@Component
public class OpenIdAuthenticationConfig
        extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    GeneralAuthenticationFailureHandler generalAuthenticationFailureHandler;

    @Autowired
    GeneralAuthenticationSuccessHandler generalAuthenticationSuccessHandler;

    @Autowired
    UserDetailsService openIdUserDetailsService;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        OpenIdAuthenticationFilter openIdAuthenticationFilter = new OpenIdAuthenticationFilter();
        // 获取容器中已经存在的AuthenticationManager对象，并传入 openIdAuthenticationFilter 里面
        openIdAuthenticationFilter.setAuthenticationManager(
                http.getSharedObject(AuthenticationManager.class));

        // 指定记住我功能
        openIdAuthenticationFilter.setRememberMeServices(http.getSharedObject(RememberMeServices.class));

        // session重复登录 管理
        openIdAuthenticationFilter.setSessionAuthenticationStrategy(
                http.getSharedObject(SessionAuthenticationStrategy.class));

        // 传入 失败与成功处理器
        openIdAuthenticationFilter.setAuthenticationSuccessHandler(generalAuthenticationSuccessHandler);
        openIdAuthenticationFilter.setAuthenticationFailureHandler(generalAuthenticationFailureHandler);

        // 构建一个OpenIdAuthenticationProvider实例，接收 openIdUserDetailsService 通过openId查询用户信息
        OpenIdAuthenticationProvider provider = new OpenIdAuthenticationProvider();
        provider.setUserDetailsService(openIdUserDetailsService);

        // 将provider绑定到 HttpSecurity上，并将 手机号认证过滤器绑定到用户名密码认证过滤器之后
        http.authenticationProvider(provider)
                .addFilterAfter(openIdAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

    }
}
